package com.farm.web.filter.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang.StringUtils;

public class NginxRequestWrapper extends HttpServletRequestWrapper {

	public NginxRequestWrapper(HttpServletRequest request) {
		super(request);
	}

//http
	public java.lang.String getScheme() {
		String scheme = super.getHeader("X-Http-scheme");
		if(StringUtils.isBlank(scheme)) {
			scheme = super.getHeader("X-Forwarded-Scheme");
		}
		String cval = NginxConfig.getString("request.able", super.getServerName()).equals("true")
				? NginxConfig.getString("request.scheme", super.getServerName()).trim()
				: "NONE";

		if (!cval.equals("NONE")) {
			return cval;
		} else {
			if (StringUtils.isNotBlank(scheme)) {
				return scheme;
			} else {
				return super.getScheme();
			}
		}
	}

//127.0.0.1
	public java.lang.String getServerName() {
		String servername = super.getHeader("X-Forwarded-Host");
		String cval = NginxConfig.getString("request.able", super.getServerName()).equals("true")
				? NginxConfig.getString("request.host", super.getServerName()).trim()
				: "NONE";
		if (!cval.equals("NONE")) {
			return cval;
		} else {
			if (StringUtils.isNotBlank(servername)) {
				return servername;
			} else {
				return super.getServerName();
			}
		}
	}

//8080
	public int getServerPort() {
		String port = super.getHeader("X-Forwarded-Port");
		String cval = NginxConfig.getString("request.able", super.getServerName()).equals("true")
				? NginxConfig.getString("request.port", super.getServerName()).trim()
				: "NONE";
		if (!cval.equals("NONE")) {
			return Integer.valueOf(cval);
		} else {
			if (StringUtils.isNotBlank(port)) {
				return Integer.valueOf(port);
			} else {
				return super.getServerPort();
			}
		}
	}

//"/wcp"
	public String getContextPath() {
		String cval = NginxConfig.getString("request.able", super.getServerName()).equals("true")
				? NginxConfig.getString("request.path", super.getServerName()).trim()
				: "NONE";
		if (!cval.equals("NONE")) {
			return cval;
		} else {
			return super.getContextPath();
		}
	}

}
